package com.destin.basic.controller.system;

import com.destin.basic.config.RedisUtils;
import com.destin.basic.constans.RedisKey;
import com.destin.basic.dto.LoginInfoDTO;
import com.destin.basic.exception.BusinessException;
import com.destin.basic.service.admin.AdminService;
import com.destin.basic.util.JsonResponse;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * @author: Destin
 * @date: 2022-02-23
 */
@Api("登录接口")
@RestController
@RequestMapping("login")
public class LoginController {

    @Resource
    RedisUtils redisUtils;
    @Resource
    Producer producer;
    @Resource
    AdminService adminService;

    @PostMapping("/in")
    @ApiOperation("登录")
    public JsonResponse<String> loginMain(@RequestBody LoginInfoDTO loginInfoDTO) {
        String username = loginInfoDTO.getUsername();
        String password = loginInfoDTO.getPassword();
        String code = loginInfoDTO.getCode();
        String uuid = loginInfoDTO.getUuid();
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            throw BusinessException.create("用户名或者密码不能为空");
        if(StringUtils.isEmpty(code))
            throw BusinessException.create("验证码不能为空");
        String trueCode = (String) redisUtils.get(RedisKey.getLoginImgCodeKey(uuid));
        if(StringUtils.isEmpty(trueCode) || !trueCode.toLowerCase().equals(code.toLowerCase())) {
            redisUtils.del(RedisKey.getLoginImgCodeKey(uuid));
            throw BusinessException.create("验证码错误");
        }
        String token = adminService.login(username, password);
        if (token == null) {
            throw BusinessException.create("用户名或密码错误");
        }
        redisUtils.del(RedisKey.getLoginImgCodeKey(uuid));
        return JsonResponse.ok(token);
    }

    @GetMapping("/captcha")
	@ApiOperation("验证码获取")
    public JsonResponse<String> captcha(String uuid) {
        String captcha = doCaptcha(uuid);
        if (captcha != null) {
            return JsonResponse.ok(captcha);
        }
        return JsonResponse.error("获取验证码失败");
    }

    private String doCaptcha(String uuid) {
        // 生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        redisUtils.setCacheObject(RedisKey.getLoginImgCodeKey(uuid), text, 5, TimeUnit.MINUTES);
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        } catch (IOException e) {
            return null;
        }
    }
}
